package com.example.supplychainbackend.controller;

import com.example.supplychainbackend.controller.dto.DataResponse;
import com.example.supplychainbackend.service.FileService;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
public class FileController {

    private final FileService fileService;

    @PostMapping("/upload")
    public DataResponse<String> uploadFile(
            @RequestParam("file") MultipartFile file) throws IOException {
        // 存储文件并获取URL
        String fileUrl = fileService.storeFile(file);
        return DataResponse.success(fileUrl);
    }

    @DeleteMapping("/file")
    public DataResponse<String> deleteFileByUrlParam(
            @RequestParam("url") String fileUrl) {
        try {
            // URL解码（防止特殊字符）
            String decodedUrl = java.net.URLDecoder.decode(fileUrl, "UTF-8");

            boolean deleted = fileService.deleteFileByUrl(decodedUrl);

            if (deleted) {
                return DataResponse.success("删除成功");
            } else {
                return DataResponse.error(404, new Exception("文件不存在"));
            }

        } catch (Exception e) {
            return DataResponse.error(500, new Exception("删除失败"));
        }
    }

    @GetMapping("/files/{fileUrl}")
    public ResponseEntity<Resource> previewFile(@PathVariable String fileUrl) {
        try {
            fileUrl = "/files/" + fileUrl;
            Resource resource = fileService.loadFileAsResource(fileUrl);
            MediaType mediaType = fileService.getMediaType(fileUrl);

            return ResponseEntity.ok()
                    .contentType(mediaType)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline")
                    .body(resource);

        } catch (IOException e) {
            return ResponseEntity.notFound().build();
        }
    }

//    @GetMapping("/files/{fileUrl}")
//    public ResponseEntity<Resource> downloadFile(@PathVariable String fileUrl) {
//        try {
//            fileUrl = "/files/" + fileUrl;
//            Resource resource = loadFileAsResource(fileUrl);
//            MediaType mediaType = getMediaType(fileUrl);
//
//            return ResponseEntity.ok()
//                    .contentType(mediaType)
//                    .header(HttpHeaders.CONTENT_DISPOSITION,
//                            "attachment; filename=\"" + resource.getFilename() + "\"")
//                    .body(resource);
//
//        } catch (IOException e) {
//            return ResponseEntity.notFound().build();
//        }
//    }

    @ExceptionHandler(Exception.class)
    public DataResponse<Exception> fileErrorHandler(Exception e) {
        return DataResponse.error(500,e);
    }
}